import cv2

class Tf25aCamera:
    def __init__(self, device, name):
        self.device = device
        self.name = name
        self.cap = None

    def open(self, width=256, height=194, fps=30):
        self.cap = cv2.VideoCapture(self.device, cv2.CAP_V4L2)
        if not self.cap.isOpened():
            print(f"[ERROR] 无法打开红外摄像头 {self.name} ({self.device})")
            return False

        # 设置像素格式为UYUV
        success = self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'UYVY'))
        if not success:
            print(f"[WARNING] 设置UYUV格式失败，使用默认格式")

        # 设置摄像头参数
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        self.cap.set(cv2.CAP_PROP_FPS, fps)
        
        print(f"[INFO] 打开红外摄像头 {self.name} ({self.device}) 成功")
        return True

    def read(self):
        if not self.cap or not self.cap.isOpened():
            print(f"[ERROR] 红外摄像头 {self.name} 未打开或已关闭")
            return None

        ret, frame = self.cap.read()
        if not ret:
            print(f"[ERROR] 读取红外摄像头 {self.name} 图像失败")
            return None
            
        return frame

    def is_opened(self):
        return self.cap and self.cap.isOpened()

    def release(self):
        if self.cap:
            self.cap.release()
            self.cap = None
            print(f"[INFO] 红外摄像头 {self.name} 资源已释放")
